<template>
  <view class="tree-menu">
    <view class="tree-title">居民电子健康档案首页</view>

    <view class="tree-container">
      <!-- 个人健康标识 -->
      <view class="tree-node level-1" @click="navigateTo('/pinggu/marks/my-tag')">
        <view class="node-content">
          <!-- <IconFont :name="expandedNodes['health-id'] ? 'minus' : 'plus'" size="16" /> -->
          <text class="node-text">个人健康标识</text>
        </view>
      </view>

      <!-- 个人基本健康信息 -->
      <view class="tree-node level-1">
        <view class="node-content" @click="toggleNode('basic-health')">
          <IconFont :name="expandedNodes['basic-health'] ? 'minus' : 'plus'" size="16" />
          <text class="node-text">个人基本健康信息</text>
        </view>

        <view v-if="expandedNodes['basic-health']" class="children">
          <!-- 用户基本信息 -->
          <view class="tree-node level-2">
            <view class="node-content" @click="toggleNode('user-basic')">
              <IconFont :name="expandedNodes['user-basic'] ? 'minus' : 'plus'" size="16" />
              <text class="node-text">用户基本信息</text>
            </view>
            <view v-if="expandedNodes['user-basic']" class="children">
              <view class="tree-node level-3" @click="navigateTo('/pages/info/personal-person-detail/list')">
                <view class="node-content">
                  <text class="node-text">服务对象个人基本信息</text>
                </view>
              </view>

              <view class="tree-node level-3" @click="navigateTo('/pages/info/guardian/list')">
                <view class="node-content">
                  <text class="node-text">用户（监护人）信息</text>
                </view>
              </view>

              <view class="tree-node level-3" @click="navigateTo('/pages/info/demographic-body/list')">
                <view class="node-content">
                  <text class="node-text">下单人信息</text>
                </view>
              </view>

              <view class="tree-node level-3" @click="navigateTo('/pages/info/personal-manager/list')">
                <view class="node-content">
                  <text class="node-text">健康管理人（健康管家）基本信息</text>
                </view>
              </view>

              <view class="tree-node level-3" @click="navigateTo('/pages/info/personal-person-detail-contact/list')">
                <view class="node-content">
                  <text class="node-text">与客户端-我的关联</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 人口学信息 -->
          <view class="tree-node level-2" @click="navigateTo('/pages/info/demographic/edit')">
            <view class="node-content">
              <text class="node-text">人口学信息</text>
            </view>
          </view>

          <!-- 社会经济学信息 -->
          <view class="tree-node level-2" @click="navigateTo('/pages/info/socioeconomic/list')">
            <view class="node-content">
              <text class="node-text">社会经济学信息</text>
            </view>
          </view>

          
          <!-- 紧急联系人信息 -->
          <view class="tree-node level-2" @click="navigateTo('/pages/info/emergency-contact/list')">
            <view class="node-content">
              <text class="node-text">紧急联系人信息</text>
            </view>
          </view>

          <!-- 建档信息 -->
          <view class="tree-node level-2" @click="navigateTo('/pages/info/health-live-habits/list')">
            <view class="node-content">
              <text class="node-text">建档信息</text>
            </view>
          </view>
          
          <!-- 家庭医生签约信息 -->
          <view class="tree-node level-2" @click="navigateTo('/pages/info/family-doctor/list')">
            <view class="node-content">
              <text class="node-text">家庭医生签约信息</text>
            </view>
          </view>

          <!-- 基础健康信息 -->
          <view class="tree-node level-2" @click="navigateTo('/pages/info/health-exam/list')">
            <view class="node-content">
              <text class="node-text">基础健康信息</text>
            </view>
          </view>
        </view>
      </view>
      <view class="tree-node level-1" @click="navigateTo('/pages/historys/index/index')">
        <view class="node-content">
          <text class="node-text">既往病史</text>
        </view>
      </view>
    </view>

    <!-- 设置token -->
    <view class="token-section">
      <view class="token-input-container">
        <input 
          class="token-input" 
          v-model="tokenValue" 
          placeholder="请输入token"
          type="text"
        />
        <nut-button class="token-button" @click="saveToken">确定</nut-button>
      </view>
    </view>

    <view class="token-section">
      <view class="token-input-container">
        <input 
          class="token-input" 
          v-model="openidValue" 
          placeholder="请输入openid"
          type="text"
        />
        <nut-button class="token-button" @click="saveOpenid">确定</nut-button>
      </view>
    </view>

    <view class="my-4 flex gap-4 flex-wrap">
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/assessSpecialInfo/list' })">健康评估</nut-button>
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/assessPhysiFuncInfo/list' })">生理功能评估</nut-button>
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/assessIcfFuncInfo/list' })">自理能力评估</nut-button>
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/assessRiskInfo/list' })">风险和并发症评估</nut-button>
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/assessGeneralInfo/list' })">一般健康状况评估</nut-button>
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/healthSocialInfo/list' })">社会经济学评估</nut-button>
      <nut-button @click="Taro.navigateTo({ url: '/pinggu/healthRecordInfo/list' })">人口学基本信息表</nut-button>
    </view>

    <!-- H5页面导航按钮 -->
    <view class="token-section">
      <view class="token-input-container">
        <nut-button class="token-button" @click="chooseImage" style="width: 100%;">上传图片</nut-button>
      </view>
    </view>

  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import Taro, { hideLoading, showLoading, getEnv } from '@tarojs/taro';
import { storeToRefs } from 'pinia';
import { useNurseUser } from '@/service';
import { useNursesStore, useAuthStore } from '@/store';
import { useGetAuthInfo, useAuthLogin, useNurseAuthLogin, useNurseGetAuthInfo, useGetOpenid } from '@/hooks';
import { localStg } from '@/utils';
import { getDemographicInfo } from "./tooler";
import { getDictWithCache } from "@/service/api/dict";
// import UserHome from './components/userhome.vue';
// import NursesHome from './components/nurseshome.vue';

definePageConfig({
  navigationStyle: 'custom',
  navigationBarTitleText: '安好护理',
  enablePullDownRefresh: true
});

const { nurseNurses, openid: nurse_openid } = storeToRefs(useNursesStore());

const { openid, nurseUser } = storeToRefs(useAuthStore());
// import { useGetPhone, useGetOpenid } from '@/hooks';

const { refreshSpecial, getVisibleByHospital } = useNurseUser();

// onMounted(() => {
//   getDemographicInfo(openid.value);
// })


async function initAuth() {
  const openid_Stg = localStg.get('openid');
  console.log(openid_Stg, "openid_Stg---------=======================");

  if (openid_Stg) {
    showLoading({ title: '正在请求...' });
    openid.value = openid_Stg;
    await useAuthLogin();
    await useGetAuthInfo();
    console.log(nurseUser.value, "nurseUser.value-@@@===============");
    if (nurseUser.value.id) refreshSpecial(nurseUser.value.id);
    hideLoading();

    // const res = await getDemographicInfo(nurseUser.value.idNumber);
    // const res = await getDemographicInfo('452225198403150039');
    // console.log(res, "res----555");
    // if(res){
    //   localStg.set("demographicInfo", res);
    //    const obj = localStg.get("demographicInfo");
    //   console.log(obj, "obj-----3333===");

    //   const rs = await getDictWithCache("job_type");
    //   console.log(rs, "code")
    // }
  }
  else{
    // useGetOpenid()
  }

  const nurseopenid = localStg.get('nurse_openid');
  if (nurseopenid) {
    showLoading({ title: '正在请求...' });
    nurse_openid.value = nurseopenid;
    await useNurseAuthLogin();
    await useNurseGetAuthInfo();
    hideLoading();
  }

  // Taro.login({
  //   success: (res) => {
  //     console.log(res, "res---------=======================");
  //     useGetPhone(res.code);
  //   }
  // });
}

initAuth();

// 展开状态管理
const expandedNodes = ref({
  'health-id': false,
  'basic-health': true,
  'user-basic': true
});

// token输入值
const tokenValue = ref('');

// 保存token到localStorage
const saveToken = () => {
  if (tokenValue.value.trim()) {
    // Taro.setStorageSync('token', tokenValue.value.trim());
    localStg.set("token", tokenValue.value.trim())
    Taro.showToast({
      title: 'Token保存成功',
      icon: 'success',
      duration: 2000
    });
    tokenValue.value = ''; // 清空输入框
  } else {
    Taro.showToast({
      title: '请输入token',
      icon: 'error',
      duration: 2000
    });
  }
};

const openidValue = ref('');
const saveOpenid = () => {
  localStg.set("openid", openidValue.value)
  // location.reload();
  // Taro.setStorageSync('openid', '1234567890');
};

// 切换节点展开状态
const toggleNode = (nodeKey) => {
  expandedNodes.value[nodeKey] = !expandedNodes.value[nodeKey];
};

// 导航到指定页面
const navigateTo = (url) => {
  Taro.navigateTo({ url });
};

const chooseImage = () => {
  Taro.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => { 
      console.log("res", res)
      uploadAvatar(res.tempFilePaths[0])
    }
  })
}

async function uploadAvatar(filePath: string) {
  console.log("filePath", filePath)
  
  // H5环境下使用相对路径，避免跨域和端口问题
  const isH5 = getEnv() === 'WEB'
  const uploadUrl = isH5 
    ? '/api/file-service/FileUpload/custom_saveImage'
    : 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage'
  
  try {
    // 获取token
    const token = localStg.get('token') || ''
    console.log('上传使用的token:', token)
    
    // H5环境下先尝试使用原生fetch API
    if (isH5) {
      try {
        console.log('尝试使用fetch API上传...')
        const response = await fetch(filePath)
        const blob = await response.blob()
        const file = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
        
        const formData = new FormData()
        formData.append('file', file)
        
        const headers: HeadersInit = {}
        if (token) {
          headers['X-Access-Token'] = token
        }
        
        const fetchResponse = await fetch(uploadUrl, {
          method: 'POST',
          body: formData,
          headers,
        })
        
        console.log('fetch上传响应状态:', fetchResponse.status)
        
        if (fetchResponse.ok) {
          const responseData = await fetchResponse.text()
          console.log('fetch上传成功，返回数据:', responseData)
          Taro.showToast({
            title: '上传成功',
            icon: 'success'
          })
          return
        } else {
          console.error('fetch上传失败，状态码:', fetchResponse.status)
        }
      } catch (fetchError) {
        console.log('fetch上传失败，尝试Taro.uploadFile:', fetchError)
      }
    }
    
    // 使用Taro.uploadFile作为备选方案
    Taro.uploadFile({
        url: uploadUrl, // 替换为你的后端接口地址
        filePath: filePath,
        name: 'file', // 后端接收文件的字段名
        fileName: 'avatar.jpg', // 文件名
        formData: {
          
        },
        header: {
          'content-type': 'multipart/form-data',
          ...(token ? { 'X-Access-Token': token } : {})
        },
        success: (uploadRes) => {
          console.log('上传成功', uploadRes);
          Taro.showToast({
            title: '上传成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error('上传失败', err);
          Taro.showToast({
            title: '上传失败',
            icon: 'error'
          })
        }
    });
  } catch (error) {
    console.error('上传异常:', error)
    Taro.showToast({
      title: '上传失败',
      icon: 'error'
    })
  }
}

</script>

<style lang="scss" scoped>
.tree-menu {
  padding: 40rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.tree-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 40rpx;
  text-align: center;
  padding: 30rpx;
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.tree-container {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.tree-node {
  border-bottom: 2rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &.level-1 {
    .node-content {
      padding: 30rpx 40rpx;
      background: #fafafa;
      font-weight: 600;
      color: #333;
    }
  }

  &.level-2 {
    .node-content {
      padding: 24rpx 40rpx 24rpx 80rpx;
      background: white;
      color: #555;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 50rpx;
        top: 0;
        bottom: 0;
        width: 2rpx;
        background: #e0e0e0;
      }

      &::after {
        content: '';
        position: absolute;
        left: 50rpx;
        top: 50%;
        width: 20rpx;
        height: 2rpx;
        background: #e0e0e0;
      }
    }
  }

  &.level-3 {
    .node-content {
      padding: 20rpx 40rpx 20rpx 120rpx;
      background: #f9f9f9;
      color: #666;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 90rpx;
        top: 0;
        bottom: 0;
        width: 2rpx;
        background: #e0e0e0;
      }

      &::after {
        content: '';
        position: absolute;
        left: 90rpx;
        top: 50%;
        width: 20rpx;
        height: 2rpx;
        background: #e0e0e0;
      }
    }

    &:hover .node-content {
      background: #e3f2fd;
      color: #1976d2;
    }
  }
}

.node-content {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: #f0f0f0;
  }

  &:active {
    background: #e0e0e0;
  }
}

.node-text {
  flex: 1;
  margin-left: 16rpx;
  font-size: 28rpx;
  line-height: 1.4;
}

.children {
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
  }

  to {
    opacity: 1;
    max-height: 2000rpx;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tree-menu {
    padding: 20rpx;
  }

  .tree-title {
    font-size: 28rpx;
    padding: 30rpx;
  }

  .tree-node {
    &.level-1 .node-content {
      padding: 30rpx;
    }

    &.level-2 .node-content {
      padding: 24rpx 30rpx 24rpx 70rpx;

      &::before {
        left: 40rpx;
      }

      &::after {
        left: 40rpx;
      }
    }

    &.level-3 .node-content {
      padding: 20rpx 30rpx 20rpx 100rpx;

      &::before {
        left: 70rpx;
      }

      &::after {
        left: 70rpx;
      }
    }
  }

  .node-text {
    font-size: 28rpx;
    line-height: 1.5;
  }
}

// Token设置区域样式
.token-section {
  margin-top: 40rpx;
  padding: 30rpx;
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.token-input-container {
  display: flex;
  gap: 20rpx;
  align-items: center;
}

.token-input {
  flex: 1;
  padding: 20rpx 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  background: #fafafa;
  transition: all 0.3s ease;

  &:focus {
    outline: none;
    border-color: #1976d2;
    background: white;
    box-shadow: 0 0 0 4rpx rgba(25, 118, 210, 0.1);
  }

  &::placeholder {
    color: #999;
  }
}

.token-button {
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  width: 180rpx;

  &:hover {
    background: #1565c0;
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.3);
  }

  &:active {
    background: #0d47a1;
    transform: translateY(0);
  }
}
</style>
